//
//  DynamicChangeIconViewController.m
//  TestPrj
//
//  Created by 朱铅峰 on 2020/6/1.
//  Copyright © 2020 Xing. All rights reserved.
//

#import "DynamicChangeIconViewController.h"
#import <Masonry.h>
#import <objc/runtime.h>
#import <Toast.h>

@interface DynamicChangeIconViewController ()

@property(nonatomic,strong)NSArray *weathers;

@end

@implementation DynamicChangeIconViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.title = @"动态更换图标";
    self.view.backgroundColor = [UIColor blueColor];
    self.weathers = @[@"晴", @"多云", @"小雨", @"大雨", @"雪", @""];
    
    //1.在info.plist中设置Icon files (iOS 5)属性，具体看配置
    //2.可以设置多尺寸也可以不设置，本案例中，晴为多尺寸，其他不是
    //3.通常调用完更新图标的API后，应用是会有弹窗提示的，本案例中，通过Method swizzling hook该弹框,达到了静默更改的效果
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button setTitle:@"更新图标" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(resetAppIconAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    [button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.view);
    }];
}

- (void)resetAppIconAction {
    if (@available(iOS 10.3, *)) {
        if ([[UIApplication sharedApplication] supportsAlternateIcons]) {
            
            NSString *weather = self.weathers[arc4random() % self.weathers.count];
            if ([weather isEqualToString:@""]) {
                weather = nil;
            }
            
            NSLog(@"更换app图标 ： %@",weather);
            //传空会恢复成应用最初设置的图标，
            //通过Method swizzlinghook掉alert弹窗后，会得不到回调
            [[UIApplication sharedApplication] setAlternateIconName:weather completionHandler:^(NSError * _Nullable error) {
                if (error) {
                    NSLog(@"更换app图标发生错误了 ： %@",error);
                } else {
                    NSString *tip = weather;
                    if (!weather) {
                        tip = @"还原成原来的icon";
                    } else {
                        tip = [NSString stringWithFormat:@"替换新的icon：%@",weather];
                    }
                    [self.view makeToast:tip];
                }
            }];
        } else {
            [self.view makeToast:@"不支持更换图标"];
        }
    } else {
        [self.view makeToast:@"不支持更换图标"];
    }
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    [self swizzlingMethodAction];
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    
    [self swizzlingMethodAction];
}

- (void)swizzlingMethodAction {
    
    //如果放在load方法里的话，会对所有ViewController产生影响（放到Category也是一样的）
    //为了避免这种情况发生，在viewWillAppear和viewWillDisappear都调用改方法
    Method presentM = class_getInstanceMethod(self.class, @selector(presentViewController:animated:completion:));
    Method presentSwizzlingM = class_getInstanceMethod(self.class, @selector(dy_presentViewController:animated:completion:));

    method_exchangeImplementations(presentM, presentSwizzlingM);
}

//+ (void)load {
//
//    static dispatch_once_t onceToken;
//    dispatch_once(&onceToken, ^{
//        Method presentM = class_getInstanceMethod(self.class, @selector(presentViewController:animated:completion:));
//        Method presentSwizzlingM = class_getInstanceMethod(self.class, @selector(dy_presentViewController:animated:completion:));
//
//        method_exchangeImplementations(presentM, presentSwizzlingM);
//    });
//}

- (void)dy_presentViewController:(UIViewController *)viewControllerToPresent animated:(BOOL)flag completion:(void (^)(void))completion {

    NSLog(@"_____func:%s",__func__);
    if ([viewControllerToPresent isKindOfClass:[UIAlertController class]]) {
        NSLog(@"title : %@",((UIAlertController *)viewControllerToPresent).title);
        NSLog(@"message : %@",((UIAlertController *)viewControllerToPresent).message);

        UIAlertController *alertController = (UIAlertController *)viewControllerToPresent;
        if (alertController.title == nil && alertController.message == nil) {
            return;
        } else {
            [self dy_presentViewController:viewControllerToPresent animated:flag completion:completion];
            return;
        }
    }

    [self dy_presentViewController:viewControllerToPresent animated:flag completion:completion];
}

@end


